/**
 * Copyright 2007 American Well Systems
 * All rights reserved.
 *
 * It is illegal to use, reproduce or distribute
 * any part of this Intellectual Property without
 * prior written authorization from American Well.
 */
package org.rich.charlesmurphy.core.filters;

import org.ddevil.data.Data;
import org.ddevil.data.Filter;
import org.springframework.util.StringUtils;

/**
 * Filters out requests based on a regular expression.
 * @author Rich O'Connell
 */
public class DataRegexFilter implements Filter<Data> {
	private String id;
	private String regex;
	private boolean required;
	private boolean negate;

	/**
	 * @param attributeId the attribute that will be checked against
	 */
	public DataRegexFilter(String attributeId, String regex) {
		this(attributeId, regex, true, false);
	}

	public DataRegexFilter(String attributeId, String regex, boolean required, boolean negate) {
		setAttributeId(attributeId);
		setRegex(regex);
		setRequired(required);
		setNegate(negate);
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean accept(Data object) {
		String v = (String)object.getValue(id);
		if (!StringUtils.hasText(v) && required) {
			return false;
		}
		if (v == null) {
			v = "";
		}
		boolean matches = v.matches(regex);
		return  (matches && !negate) || (!matches && negate);
	}

	public void setAttributeId(String attribute) {
		id = attribute;
	}
	/**
	 * @param regex the regex to set
	 */
	public void setRegex(String regex) {
		this.regex = regex;
	}

	/**
	 * @param required the required to set
	 */
	public void setRequired(boolean required) {
		this.required = required;
	}

	/**
	 * @param negate the negate to set
	 */
	public void setNegate(boolean negate) {
		this.negate = negate;
	}

}
